<template>
  <el-input v-model="usename" placeholder="请输入账号" clearable maxlength="20" />
  <el-input v-model="usepassword" type="password" placeholder="请输入密码" show-password clearable maxlength="20" />
  <el-input v-model="saveCode" class="saveCode" clearable maxlength="4" placeholder="请输入验证码" />
  <span>
    <img :src="codeAddress" alt="验证码">
  </span>
  <el-checkbox v-model="checked" label="记住密码" size="large" />
  <a href="javaScript:;">忘记密码？</a>
  <div class="login_btn" @click="toLogin">登录</div>
</template>
<script setup>

import { ref, onMounted, reactive } from 'vue'

/* 引入快捷组件 */
import utils from "@/utils/utils.js"
import httpHelper from '@/api/httpHelper';

/* 引入路由 */
import router from '@/router';

/* 引入state */
import { useStore } from "vuex";
let store = useStore();

/* 输入框内容 */
const usename = ref('');
const usepassword = ref('');
const saveCode = ref('');

/* 验证码图片地址 */
const codeAddress = ref('');

onMounted(() => {
  getCheckCode();
  getCookie(); // 读取cookie中的账号密码
});

/* 获取验证码 */
const getCheckCode = () => {
  httpHelper.post("/users/getCheckCode",
    {},
    (res) => {
      console.log(res);
      /* 通过将图片流转成blob，再通过blob创建url */
      // let blob = new Blob([res.data],{type: "image/png"});
      // let url = window.URL.createObjectURL(blob);
      // console.log(res.data);
      // codeAddress.value = url.slice(url.indexOf(':')+1);
      // console.log(res.data.data.url);
      codeAddress.value = 'http://192.168.0.113:80/' + res.data.data.url;
    }, (err) => {
      console.log(err);
    })
}

let userData = reactive({});
/* 登录按钮 */
const toLogin = () => {
  if (usename.value && usepassword.value && saveCode.value) {
    const userNum = usename.value;
    const userPassword = usepassword.value;
    const checkCode = saveCode.value;
    httpHelper.post("/users/login", { userNum, userPassword, checkCode }, (res) => {
      console.log(res);
      if (res.data.code == 20000) {
        /* 判断是否记住密码 */
        if (checked.value) {
          setCookie(usename.value, usepassword.value, true, 7);
        } else {
          clearCookie();
        }
        userData = res.data.data.logUser;
        store.commit('saveUserData', userData);
        let roleId = store.state.userData.roleId;
        router.push({ path: '/home', query: { roleId } });
      } else {
        utils.showError(res.data.message);
      }
    }, (err) => {
      console.log(err);
    })
  } else {
    utils.showError('请输入完整的信息！');
  }
}

/* 记住密码 */
let checked = ref();

/* 设置cookie */
const setCookie = (c_name, c_pwd, c_state, exdays) => {
  const exdate = new Date()
  exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays) // 保存的天数
  window.document.cookie = `username=${c_name};path=/;expires=${exdate.toGMTString()}`
  window.document.cookie = `password=${c_pwd};path=/;expires=${exdate.toGMTString()}`
  window.document.cookie = `state=${c_state};path=/;expires=${exdate.toGMTString()}`
}

/* 读取cookie */
const getCookie = () => {
  if (document.cookie.length > 0) {
    const arr = document.cookie.split('; ')
    for (let i = 0; i < arr.length; i++) {
      const arr2 = arr[i].split('=')
      if (arr2[0] === 'username') {
        usename.value = arr2[1]
      } else if (arr2[0] === 'password') {
        usepassword.value = arr2[1]
      } else if (arr2[0] === 'state') {
        checked.value = Boolean(arr2[1])
      }
    }
  }
}

/* 清除cookie */
const clearCookie = () => {
  setCookie('', '', false, -1)
}

</script>
<style scoped>
.el-input {
  height: 50px;
  margin-bottom: 30px;
}

.saveCode {
  width: 60%;
}

span {
  display: inline-block;
  width: 40%;
  text-align: center;
  vertical-align: top;
}

img {
  display: inline-block;
  width: 100%;
  vertical-align: middle;
  height: 50px;
}

a {
  float: right;
  color: #606266;
  margin-top: 10px;
  font-size: 14px;
}

.login_btn {
  height: 50px;
  text-align: center;
  line-height: 50px;
  border-radius: 7px;
  margin-top: 20px;
  background-color: #6c9dbd;
  cursor: pointer;
}
</style>
